from inspect import cleandoc
import logging

import numpy as np
import torch
from matplotlib import pyplot as plt
from scipy.special import expit as sigmoid

from .owl_utils import draw_bbox_with_label


class BBoxVisualizer:
    """
    A example node

    Class methods
    -------------
    INPUT_TYPES (dict):
        Tell the main program input parameters of nodes.
    IS_CHANGED:
        optional method to control when the node is re executed.

    Attributes
    ----------
    RETURN_TYPES (`tuple`):
        The type of each element in the output tuple.
    RETURN_NAMES (`tuple`):
        Optional: The name of each output in the output tuple.
    FUNCTION (`str`):
        The name of the entry-point method. For example, if `FUNCTION = "execute"` then it will run Example().execute()
    OUTPUT_NODE ([`bool`]):
        If this node is an output node that outputs a result/image from the graph. The SaveImage node is an example.
        The backend iterates on these output nodes and tries to execute all their parents if their parent graph is properly connected.
        Assumed to be False if not present.
    CATEGORY (`str`):
        The category the node should appear in the UI.
    execute(s) -> tuple || None:
        The entry point method. The name of this method must be the same as the value of property `FUNCTION`.
        For example, if `FUNCTION = "execute"` then this method's name must be `execute`, if `FUNCTION = "foo"` then it must be `foo`.
    """
    def __init__(self):
        pass

    @classmethod
    def INPUT_TYPES(s):
        """
            Return a dictionary which contains config for all input fields.
            Some types (string): "MODEL", "VAE", "CLIP", "CONDITIONING", "LATENT", "IMAGE", "INT", "STRING", "FLOAT".
            Input types "INT", "STRING" or "FLOAT" are special values for fields on the node.
            The type can be a list for selection.

            Returns: `dict`:
                - Key input_fields_group (`string`): Can be either required, hidden or optional. A node class must have property `required`
                - Value input_fields (`dict`): Contains input fields config:
                    * Key field_name (`string`): Name of a entry-point method's argument
                    * Value field_config (`tuple`):
                        + First value is a string indicate the type of field or a list for selection.
                        + Second value is a config for type "INT", "STRING" or "FLOAT".
        """

        return {
            "required": {
                "image": ("IMAGE", { "tooltip": "This is an image"}),
                "boxes": ("BOXES",),
                "confidences": ("CONFIDENCES",),
                "threshold": ("FLOAT", {
                    "default": 0.2,
                    #"min": 0.1,
                    "max": 1,
                    "step": 0.1,
                    "round": 0.001,
                    "display": "number"
                }),
                "font_scale": ("FLOAT", {
                    "default": 1.0,
                    "min": 0.1,
                    "max": 96,
                    "step": 1,
                    "round": 0.1,
                    "display": "number"
                }),
                "line_width": ("INT", {
                    "default": 2,
                    "min": 1, #Minimum value
                    "max": 128, #Maximum value
                    "step": 1, #Slider's step
                    "display": "number" # Cosmetic only: display as "number" or "slider"
                }),
            },
        }

    RETURN_TYPES = ("IMAGE",)
    RETURN_NAMES = ("Annotated Image",)
    DESCRIPTION = cleandoc(__doc__) # type: ignore
    FUNCTION = "bbox_vis"

    #OUTPUT_NODE = False
    #OUTPUT_TOOLTIPS = ("",) # Tooltips for the output node

    CATEGORY = "OWL"

    def bbox_vis(self, image, boxes, confidences, threshold: float, font_scale: float, line_width: int):
        # Make a copy of the image to avoid modifying the original
        img_with_bbox = np.asarray(image).copy()

        unpacked_objectnesses = np.asarray(confidences.cpu()[0].detach())
        unpacked_boxes = np.asarray(boxes.cpu()[0].detach())

        # Let's show the top_k patches
        top_k = 32
        unpacked_objectnesses = sigmoid(unpacked_objectnesses)
        objectness_threshold = np.partition(unpacked_objectnesses, -top_k)[-top_k]

        colorMap = plt.get_cmap('tab10')

        for i, (box, objectness) in enumerate(zip(unpacked_boxes, unpacked_objectnesses)):
            if objectness < objectness_threshold:
                continue

            if any([c < 0 for c in box]):
                logging.error("Negative coordinate found, skipping")
                continue

            color = [c*255 for c in colorMap(i % colorMap.N)]
            test = draw_bbox_with_label(
                img_with_bbox,
                bbox=box,
                label='%d: %.3f' % (i, objectness),
                font_scale=font_scale,
                thickness=line_width,
                color=color
            )

        #Image.fromarray(img_with_bbox, 'RGB')
        return (torch.from_numpy(img_with_bbox),)
